package com.eddie.juc.locks;

import com.eddie.juc.IThreadPool;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author Eddie
 * @date 2022/08/19 12:43
 **/
public class ReEntryLockDemo {


    public synchronized void m1() {
        //在外层使用锁之后，在内层依然可以使用，并且不发生死锁，这样的锁就叫做重入锁
        System.out.println(Thread.currentThread().getName() + "\tcome in");
        m2();
        System.out.println(Thread.currentThread().getName() + "\tend");
    }

    public synchronized void m2() {
        System.out.println(Thread.currentThread().getName() + "\tcome in");
        m3();
    }

    public synchronized void m3() {
        System.out.println(Thread.currentThread().getName() + "\tcome in");
    }

    static Lock lock = new ReentrantLock();

    public static void main(String[] args) {
        IThreadPool threadPool = IThreadPool.getInstance();
        threadPool.execute(() -> {
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + "\tcome in外层调用");
                lock.lock();
                try {
                    System.out.println(Thread.currentThread().getName() + "\tcome in内存层调用");
                } finally {
                    lock.unlock();
                }
            } finally {
                lock.unlock();
            }
        });

        threadPool.execute(() -> {
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + "\tcome in外层调用");
            } finally {
                lock.unlock();
            }
        });
        threadPool.shutdown();
    }

    private static void reaEntryM1(IThreadPool threadPool) {
        final Object o = new Object();
        threadPool.execute(() -> {
            synchronized (o) {
                System.out.println(Thread.currentThread().getName() + "\t外层调用");
                synchronized (o) {
                    System.out.println(Thread.currentThread().getName() + "\t中层调用");
                    synchronized (o) {
                        System.out.println(Thread.currentThread().getName() + "\t内层调用");
                    }
                }
            }
        });
    }
}
